package com.sxhuayuan.parking.dao;

import java.util.List;

import javax.transaction.Transactional;

import com.sxhuayuan.parking.entity.Agent;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import com.sxhuayuan.parking.compenent.domain.IdName;
import com.sxhuayuan.parking.entity.ParkingLot;

public interface ParkingLotDao extends BaseDao<ParkingLot, Long> {

	/** 根据车场标识查询 */
	@Query(value = "select * from hypk_parking_lot where sn = ?1", nativeQuery = true)
	ParkingLot findBySn(String sn);

	/** 根据车场名字查询 */
	@Query(value = "select * from hypk_parking_lot where name = ?1", nativeQuery = true)
	ParkingLot findByCarName(String name);

	/** 根据id查询 */
	@Query(value = "select * from hypk_parking_lot where id = ?1", nativeQuery = true)
	ParkingLot findByMyId(Long id);

	/** 删除代理添加的车场 */
	@Transactional
	@Modifying
	@Query(value = "delete from hypk_parking_lot where agent_id = ?1", nativeQuery = true)
	void deleteByAgent(Long id);

	/** 删除操作人员对应的车场 */
	@Transactional
	@Modifying
	@Query(value = "delete from hypk_parking_lot where admin_id = ?1", nativeQuery = true)
	void deleteAdminCar(Long id);

	/** 根据操作员查询 */
	@Query(value = "select * from hypk_parking_lot where admin_id = ?1", nativeQuery = true)
	List<ParkingLot> findByAdmin(Long id);

	/** 根据代理查询 */
	@Query(value = "select * from hypk_parking_lot where agent_id = ?1", nativeQuery = true)
	List<ParkingLot> findByAgent(Long id);

	/** 根据代理查询 */
	@Query(value = "select id, name from hypk_parking_lot where agent_id = ?1 order by id desc", nativeQuery = true)
	List<IdName> findSelectOptionByAgent(Long id);

	/** 根据代理查询 */
	@Query(value = "select new com.sxhuayuan.parking.compenent.domain.IdName(id, name) from ParkingLot order by id desc")
	List<IdName> findAllSelectOption();

	@Query("select count(p.id) from ParkingLot p join AgentRelation r on p.agent=r.child where r.parent=?1")
	Long countByAgent(Agent parent);

	/** 根据代理查询(包括子代理车场) */
	@Query("select p from ParkingLot p join AgentRelation r on p.agent=r.child where r.parent=?1")
	List<ParkingLot> findByAgents(Agent parent);

	@Modifying
	@Query(value = "update ParkingLot set partnersWeight=?1 where id=?2")
	void updatePartnersWeight(String partnersWeight, Long id);
}
